package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.Movement;
import com.tanhua.model.domain.Visitors;
import com.tanhua.model.domain.mysql.User;
import com.tanhua.model.domain.mysql.UserInfo;
import com.tanhua.model.dto.MovementDto;
import com.tanhua.model.utils.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VisitorsVo;
import com.tanhua.server.MQAspect.LogConfig;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lxb哦吼吼
 * @version 1.0
 * @description: TODO
 * @date 2021/11/15 20:14
 */

@Service
public class MovementsService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MQService mqService;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @LogConfig(type = "0201",key = "move")
    public void publishMovement(MovementDto movementDto, MultipartFile[] imageContent) throws IOException {
        userFreezeService.checkUserStatus(2,UserHolder.getUserId());

        if (StringUtils.isEmpty(movementDto.getTextContent())) {
            throw new BusinessException(ErrorResult.contentError());
        }
        //
        Long userId = UserHolder.getUserId();
        //
        List<String> medias = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String upload = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            medias.add(upload);
        }
        //4、将数据封装到Movement对象
        movementDto.setUserId(userId);
        movementDto.setMedias(medias);
        //5、调用API完成发布动态
        ObjectId id = movementApi.publish(movementDto);
        mqService.sendAudi(userId, id);
    }

    @LogConfig(type = "0202",key = "move")
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //1、根据用户id，调用API查询个人动态内容（PageResult  -- Movement）
        PageResult pr = movementApi.findByUserId(userId, page, pagesize,1);
        //2、获取PageResult中的item列表对象
        List<Movement> items = (List<Movement>) pr.getItems();
        //3、非空判断
        if (BeanUtil.isEmpty(items)) {
            return pr;
        }
        //4、循环数据列表
        UserInfo userInfo = userInfoApi.findById(userId);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            //5、一个Movement构建一个Vo对象
            MovementsVo vo = MovementsVo.init(userInfo, item);
            String key = Constants.MOVEMENTS_INTERACT_KEY + item.getId();
            //
            String hashKeyLove = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();

            String hashKeyLike = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLike)) {
                vo.setHasLiked(1);
            }
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLove)) {
                vo.setHasLoved(1);
            }
            vos.add(vo);
        }
        //6、构建返回值
        pr.setItems(vos);
        return pr;
    }

    @LogConfig(type = "0202",key = "move")
    public PageResult findFriendMovements(Integer page, Integer pagesize) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、查询数据列表
        List<Movement> items = movementApi.findFriendMovements(userId, page, pagesize);
        //3、非空判断
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        //4、获取好友用户id
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        //5、循环数据列表
        Map<Long, UserInfo> userMaps = userInfoApi.findByIds(1, pagesize, userIds, new UserInfo());
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            //5、一个Movement构建一个Vo对象
            UserInfo userInfo = userMaps.get(item.getUserId());
            MovementsVo vo = MovementsVo.init(userInfo, item);
            String key = Constants.MOVEMENTS_INTERACT_KEY + item.getId();
            //
            String hashKeyLove = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();

            String hashKeyLike = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLike)) {
                vo.setHasLiked(1);
            }
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLove)) {
                vo.setHasLoved(1);
            }
            //
            vos.add(vo);
        }
        //6、构建返回值
        return new PageResult(page, pagesize, 0, vos);
    }

    @LogConfig(type = "0202",key = "move")
    public PageResult findRecommendMovements(Integer page, Integer pagesize) {
        String redisKey = Constants.MOVEMENTS_RECOMMEND + UserHolder.getUserId();
        String redisData = (String) this.redisTemplate.opsForValue().get(redisKey);
        List<Movement> list = Collections.EMPTY_LIST;
        if (StringUtils.isEmpty(redisData)) {
            list = movementApi.randomMovements(pagesize);
        } else {
            String[] split = redisData.split(",");
            if ((page - 1) * pagesize > split.length) {
                return new PageResult();
            }
            List<Long> pids = Arrays.stream(split)
                    .skip((page - 1) * pagesize)
                    .limit(pagesize)
                    .map(e -> Convert.toLong(e))
                    .collect(Collectors.toList());
            list = movementApi.findByPids(pids);
        }
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //5、循环数据列表
        Map<Long, UserInfo> userMaps = userInfoApi.findByIds(1, pagesize, userIds, new UserInfo());
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : list) {
            //5、一个Movement构建一个Vo对象
            UserInfo userInfo = userMaps.get(item.getUserId());
            MovementsVo vo = MovementsVo.init(userInfo, item);
            //
            String key = Constants.MOVEMENTS_INTERACT_KEY + item.getId();
            //
            String hashKeyLove = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();

            String hashKeyLike = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLike)) {
                vo.setHasLiked(1);
            }
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLove)) {
                vo.setHasLoved(1);
            }
            //
            vos.add(vo);
        }
        //6、构建返回值
        return new PageResult(page, pagesize, 0, vos);
    }

    @LogConfig(type = "0202",key = "movement",objId = "#movementId")
    public MovementsVo findMovementById(String movementId) {
        Movement movements = movementApi.findById(movementId);
        if (movements == null) {
            return null;
        } else {
            UserInfo userInfo = userInfoApi.findById(movements.getUserId());
            MovementsVo movementsVo = MovementsVo.init(userInfo, movements);
            //
            String key = Constants.MOVEMENTS_INTERACT_KEY + movementsVo.getId();
            //
            String hashKeyLove = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();

            String hashKeyLike = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLike)) {
                movementsVo.setHasLiked(1);
            }
            if (redisTemplate.opsForHash().hasKey(key, hashKeyLove)) {
                movementsVo.setHasLoved(1);
            }
            //
            return movementsVo;
        }
    }

    public List<VisitorsVo> queryVisitorsList() {
        User user = UserHolder.get();
        List<Visitors> visitorsList = visitorsApi.queryMyVisitor(user.getId());

        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Long> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId", Long.class);
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(1, userIds.size(), userIds, new UserInfo());

        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitor : visitorsList) {
            UserInfo userInfo = byIds.get(visitor.getVisitorUserId());
            VisitorsVo init = VisitorsVo.init(userInfo, visitor);
            visitorsVoList.add(init);
        }
        return visitorsVoList;
    }
}
